package com.yeskery.nut.view.freemarker;

import com.yeskery.nut.core.MediaType;
import com.yeskery.nut.core.NutException;
import com.yeskery.nut.core.Request;
import com.yeskery.nut.core.Response;
import com.yeskery.nut.view.BaseWebRender;
import freemarker.template.Configuration;
import freemarker.template.Template;

import java.io.StringWriter;
import java.util.Map;

/**
 * FreeMarker的web渲染器
 * @author sprout
 * @version 1.0
 * 2022-07-02 22:04
 */
public class FreeMarkerWebRender extends BaseWebRender {

    /** FreeMarker配置对象 */
    private final Configuration configuration;

    /**
     * 构建FreeMarker的web渲染器
     * @param configuration FreeMarker配置对象
     * @param mediaType 媒体类型
     */
    public FreeMarkerWebRender(Configuration configuration, MediaType mediaType) {
        super(mediaType);
        this.configuration = configuration;
    }

    /**
     * 构建FreeMarker的web渲染器
     * @param configuration FreeMarker配置对象
     * @param mediaType 媒体类型
     * @param extendAttributes 扩展属性
     */
    public FreeMarkerWebRender(Configuration configuration, MediaType mediaType, Map<String, ?> extendAttributes) {
        super(mediaType);
        super.extendAttributes = extendAttributes;
        this.configuration = configuration;
    }

    @Override
    public void render(String key, Request request, Response response) {
        try {
            Template template = configuration.getTemplate(key);
            StringWriter stringWriter = new StringWriter();
            template.process(getBaseObjectKeyAttributes(request), stringWriter);

            response.write(stringWriter.toString(), mediaType);
        } catch (Exception e) {
            throw new NutException("FreeMarker Render Failure.", e);
        }
    }
}
